<?php defined('SYSPATH') OR die('No direct access allowed.');

/**
 * Support helper class for CMS module.
 *
 * @package    Forum
 * @author     Brotkin Ivan (BIakaVeron) <BIakaVeron@gmail.com>
 * @copyright  Copyright (c) 2009 Brotkin Ivan
 */

class cmsformat_Core {

	public static function timestamp($section, $timestamp) {
		if (is_null($section)) $section = 'default';
		is_null($timestamp) AND $timestamp = time();
		is_string($timestamp) AND $timestamp = strtotime($timestamp);
		//is_numeric($timestamp) AND $timestamp = date("Y-m-d H:i:s", $timestamp);
		if (! $format = Kohana::config('format.'.$section))
		  $format = Kohana::config('format.main.default');
		if (strpos($format, '%B') !== FALSE) {
			//$ts = getdate($timestamp);
			$month = strtolower(date('F',$timestamp));
			$format = str_replace("%B", Kohana::lang('calendar._'.$month), $format);
		}
		$others = array
		(
			'%b' => 'M',
			'%a' => 'D',
			'%A' => 'l',
		);
		foreach($others as $code => $type) {
			if (FALSE === strpos($format, $code)) continue;
			$title = strtolower(date($type,$timestamp));
			$format = str_replace($code, Kohana::lang('calendar.'.$title), $format);
		}
		// %e does not works on Win32
//		$format = str_replace("%e", sprintf("%' 2d", date("j", $timestamp)), $format);
		return cmsformat::strftime($format, $timestamp);
	}

	public static function strftime($format, $ts = null) {
		if (!$ts) $ts = time();

		$mapping = array
		(
			'%C' => sprintf("%02d", date("Y", $ts) / 100),
			'%D' => '%m/%d/%y',
			'%e' => sprintf("%' 2d", date("j", $ts)),
			'%h' => '%b',
			'%n' => "\n",
			'%r' => date("h:i:s", $ts) . " %p",
			'%R' => date("H:i", $ts),
			'%t' => "\t",
			'%T' => '%H:%M:%S',
			'%u' => ($w = date("w", $ts)) ? $w : 7
		);
		$format = str_replace
		(
			array_keys($mapping),
			array_values($mapping),
			$format
		);

		return strftime($format, $ts);
	}

}